package org.dromara.app.controller;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import lombok.extern.slf4j.Slf4j;
import org.dromara.bean.domain.HisMemberAddress;
import org.dromara.bean.service.IBaseMemberAddressService;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 收货地址
 *
 * @author wangtao
 * @since 2022-06-09
 */
@RestController
@RequestMapping("/app/address")
@Slf4j
public class AMemberAddressController {

    @Autowired
    private IBaseMemberAddressService memberAddressService;

    /**
     * 分页列表
     */
    @GetMapping(value = "pageList")
    public R pageList(@RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                      @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        return R.ok(memberAddressService.page(new Page<>(pageNo, pageSize),
            new LambdaQueryWrapper<HisMemberAddress>()
                .eq(HisMemberAddress::getMemberId, loginUser.getUserId())
                .orderByDesc(HisMemberAddress::getIsDefault, HisMemberAddress::getCreateTime)
                .eq(HisMemberAddress::getDelFlag, 0)));
    }

    /**
     * 新增/编辑
     */
    @PostMapping(value = "add")
    public R add(@RequestBody HisMemberAddress hisMemberAddress) {
        String memberId = LoginHelper.getLoginUser().getUserId().toString();
        //取消已有默认收货地址
        if (ObjectUtil.isNotEmpty(hisMemberAddress) && hisMemberAddress.getIsDefault().equals(1)) {
            memberAddressService.removeDefault(memberId);
        }
        if (hisMemberAddress.getId() == null) {
            hisMemberAddress.setId(IdWorker.getIdStr())
                .setCreateTime(new Date())
                .setDelFlag(0)
                .setMemberId(memberId);
            memberAddressService.save(hisMemberAddress);
        } else {
            memberAddressService.updateById(hisMemberAddress);
        }
        return R.ok();
    }

    /**
     * 删除
     */
    @DeleteMapping(value = "remove")
    public R remove(@RequestParam(value = "id") String id) {
        memberAddressService.removeById(id);
        return R.ok();
    }


    /**
     * 根据ID获取详情
     */
    @GetMapping(value = "info")

    public R info(@RequestParam(value = "id") String id) {
        return R.ok(memberAddressService.getById(id));
    }
}

